package vn.anhqn.englishsentensetranslator.addsentense;

import java.util.ArrayList;
import java.util.List;

import vn.anhqn.englishsentensetranslator.R;
import vn.anhqn.englishsentensetranslator.adapter.CategorySpinnerAdapter;
import vn.anhqn.englishsentensetranslator.addsentense.AddCatDialog.AddCatListener;
import vn.anhqn.englishsentensetranslator.base.fragment.FragmentHaveSlidingMenu;
import vn.anhqn.englishsentensetranslator.constant.ConfigApp;
import vn.anhqn.englishsentensetranslator.constant.Constant;
import vn.anhqn.englishsentensetranslator.model.Category;
import vn.anhqn.englishsentensetranslator.model.Sentense;
import vn.anhqn.englishsentensetranslator.utils.PreferenceHelper;
import vn.anhqn.englishsentensetranslator.utils.SqliteHelper;
import vn.anhqn.englishsentensetranslator.utils.Utils;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class AddSentenseFragment extends FragmentHaveSlidingMenu implements AddCatListener, OnItemSelectedListener {

	private Spinner catSpinner;
	private SqliteHelper sqliteHeplper;
	private CategorySpinnerAdapter adapter;
	private List<Category> listCat = new ArrayList<Category>();
	private EditText editFromLang;
	private EditText editToLang;
	int indexLang;
	private boolean isFinishAfterSave = false;
	private int action = Constant.ADD_NEW;
	private int idSentense = -1;
	private int idCat = -1;
	String[] arrLanguages;
	private Button btnSave;
	private Button btnCancel;
	private boolean isFirstCatSelection = true;

	@Override
	public void setBerhaviorView(View mView) {
		sqliteHeplper = new SqliteHelper(getActivity());
		if (sqliteHeplper.getCategory(1) == null)
			sqliteHeplper.addCategory(new Category(0, getActivity().getResources().getString(R.string.default_cat)));

		indexLang = PreferenceHelper.getInstance(getActivity()).getInt(ConfigApp.PREFERENCES_LANGUAGE_INDEX, 0);
		arrLanguages = getActivity().getResources().getStringArray(R.array.language_arr);

		catSpinner = (Spinner) mView.findViewById(R.id.spin_categories);
		editFromLang = (EditText) mView.findViewById(R.id.edit_from_lang);
		editToLang = (EditText) mView.findViewById(R.id.edit_to_lang);
		mView.findViewById(R.id.imv_add_cat).setOnClickListener(this);
		mView.findViewById(R.id.imv_edit_cat).setOnClickListener(this);
		btnSave = (Button) mView.findViewById(R.id.btn_save);
		btnSave.setOnClickListener(this);
		Utils.getIntance().setFontFromAsset(btnSave, "Helvetica/helvetica-normal.ttf");
		btnCancel = (Button) mView.findViewById(R.id.btn_cancel);
		btnCancel.setOnClickListener(this);
		Utils.getIntance().setFontFromAsset(btnCancel, "Helvetica/helvetica-normal.ttf");

		listCat.clear();
		listCat.addAll(sqliteHeplper.getAllCategory());
		adapter = new CategorySpinnerAdapter(listCat, getActivity());

		catSpinner.setAdapter(adapter);
		initFirstData();
		if (idCat == -1) {
			int prePos = PreferenceHelper.getInstance(getActivity()).getInt(Constant.KEY_EXTRA_POSITION_CAT_ADDNEW, -1);
			if (prePos < listCat.size() && prePos != -1) {
				catSpinner.setSelection(prePos);
			}
		} else {
			catSpinner.setSelection(getSelectionFromId(idCat));
		}
		catSpinner.setOnItemSelectedListener(this);

	}

	private int getSelectionFromId(int id) {
		for (int i = 0; i < listCat.size(); i++) {
			if (listCat.get(i).getId() == id) {
				return i;
			}
		}
		return 0;
	}

	@Override
	public int getResLayout() {
		return R.layout.add_sentense_fragment;
	}

	@Override
	public int getidTitle() {
		return R.string.add_new_sentense;
	}

	@Override
	public void onClickView(View v) {
		int idView = v.getId();
		switch (idView) {
		case R.id.imv_add_cat:
			AddCatDialog dialog = new AddCatDialog(getActivity());
			dialog.setAddListener(this);
			dialog.show();
			break;
		case R.id.imv_edit_cat:
			AddCatDialog dialog2 = new AddCatDialog(getActivity());
			dialog2.setAddListener(this);
			dialog2.setEditCat(adapter.getItem(catSpinner.getSelectedItemPosition()));
			dialog2.show();
			// }
			break;
		case R.id.btn_save:
			saveSentense();
			break;
		case R.id.btn_cancel:
			finishThis();
			break;

		default:
			finishThis();
			break;
		}
	}

	public void saveSentense() {
		if (editFromLang.getText() != null && !editFromLang.getText().toString().isEmpty() && editToLang.getText() != null
				&& !editToLang.getText().toString().isEmpty()) {

			Sentense sentense = new Sentense(idSentense, editFromLang.getText().toString(), editToLang.getText().toString(), adapter
					.getItem(catSpinner.getSelectedItemPosition()).getId());
			long id = -1;
			if (action == Constant.ADD_NEW)
				id = sqliteHeplper.addSentense(sentense);
			else if (action == Constant.EDIT) {
				id = sqliteHeplper.updateSentenseEtoY(sentense);
			}
			if (id != -1) {
				if (action == Constant.ADD_NEW)
					Toast.makeText(getActivity(), R.string.add_sentense_success, Toast.LENGTH_SHORT).show();
				else if (action == Constant.EDIT) {
					Toast.makeText(getActivity(), R.string.update_sentense_success, Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(getActivity(), R.string.add_sentense_failed, Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getActivity(), R.string.add_sentense_field_empty, Toast.LENGTH_SHORT).show();
		}
		if (isFinishAfterSave) {
			finishThis();
		}
	}

	private void initFirstData() {
		Bundle bundle = getArguments();
		if (bundle != null) {
			editFromLang.setText(bundle.getString(Constant.KEY_EXTRA_FROM_TEXT));
			editToLang.setText(bundle.getString(Constant.KEY_EXTRA_TO_TEXT));
			isFinishAfterSave = bundle.getBoolean(Constant.KEY_EXTRA_IS_FINISH, false);
			action = bundle.getInt(Constant.KEY_EXTRA_SENTENSE_ACTION, Constant.ADD_NEW);
			idSentense = bundle.getInt(Constant.KEY_EXTRA_SENTENSE_ID, -1);
			idCat = bundle.getInt(Constant.KEY_EXTRA_CAT_ID, -1);
			bundle.putBoolean(Constant.KEY_EXTRA_IS_FINISH, false);

		}
	}

	@Override
	public void onAddClick(String catName) {
		long id = sqliteHeplper.addCategory(new Category(0, catName));
		if (id != -1) {
			listCat.add(new Category((int) id, catName));
			adapter.notifyDataSetChanged();
			catSpinner.setSelection(getSelectionFromId((int) id));
		}
	}

	@Override
	public void onEdit(Category cat) {
		adapter.getItem(catSpinner.getSelectedItemPosition()).setName(cat.getName());
		sqliteHeplper.updateCategory(cat);
		adapter.notifyDataSetChanged();
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		if (!isFirstCatSelection) {
			PreferenceHelper.getInstance(getActivity()).putInt(Constant.KEY_EXTRA_POSITION_CAT_ADDNEW, position);
		} else {
			isFirstCatSelection = false;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

}
